var app = getApp();
var ux = require('../../../../lib/ux.js');
var WxParse = require('../../../../utils/wxParse/wxParse.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    sexs: ['男', '女'],
    ages: ['18-29', '30-39', '40-49', '50以上'],
    srs: ['3000以下', '3000-6000', '6000-10000', '10000以上'],
    zys: ['国家单位', '企业老总', '办公职员', '销售人士', '自由职业', '退休老人'],
    sex:"",
    age: "",
    sr: "",
    zy: "",
    long: '',
    lan: '',
    showCityPicker: false,
    citytab: 0,
    citytabs: ["请选择"],
    adressList: [],
    cityIndex: -1,
    addressName: '',
    proviceIndex: -1,
    cityIndex: -1,
    countyIndex: -1,
    countryIndex: -1,
    provice: null,
    city: null,
    county: null,
    country: null,
    animationAddressMenu: {},
    addressMenuIsShow: false,
    pidUrl: "/api/address/pidAdderssList.do",
    youshi: "",
    mobile: "",
    name: "",
    profile: "",
    focus: false,
    redImg: '',
    tongyi: 2,
    jlzc: false,
    dlxy: false,
    card: {},
    agentType: 0,
    banrdId: null,
    userId: null,
    getAgentCard: {},
    torderUrl: "/api/memberAgent/hhrTOrder.do",
    action: "/api/memberAgent/getBanrdHHRDetails.do",
    submit: "{{submit}}"
  },
  toShopDetail: function (event) {
    var dataset = event.currentTarget.dataset;
    var shopid = dataset.shopid;
    var price = dataset.price;
    wx.navigateTo({
      url: '/pages/member/tab1/shop/detail?prices=' + price + '&id=' + shopid,
    })
  },
  sexChange: function (e) {
    this.setData({
      sex: this.data.sexs[e.detail.value]
    })
  },
  ageChange: function (e) {
    this.setData({
      age: this.data.ages[e.detail.value]
    })
  },
  srChange: function (e) {
    this.setData({
      sr: this.data.srs[e.detail.value]
    })
  },
  zyChange: function (e) {
    this.setData({
      zy: this.data.zys[e.detail.value]
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu();
    var scene = decodeURIComponent(options.scene)
    if (scene && scene != undefined && scene != "undefined") {
      var scenes = scene.split("_");
      this.setData({
        banrdId: scene
      })
     var $this = this;
     wx.login({
      success: function (res) {
        if (res.code) {
          var jscode = res.code;
          //发起网络请求
          ux.request("/api/member/isLogin.do", {
            jscode: jscode
          }, function (protocol) {
              wx.setStorageSync("token", protocol.data.token);
              wx.setStorageSync("userInfo", protocol.data.userInfo);
              wx.setStorageSync("setting", protocol.data.setting);
              $this.setData({
                userId: protocol.data.userInfo.id
              })
      var pamars = { banrdId: $this.data.banrdId }
      ux.request($this.data.action, pamars, function (protocol) {
        $this.setData({
          lists: JSON.parse(protocol.data.card.tbpcProducts),
          card: protocol.data.card
        });
        $this.getAddressList(0);
        $this.getShar();
        WxParse.wxParse('articleDetail', 'html', protocol.data.card.tbpcXy, $this);
          }, true);
        },true); 
      } else {
        console.log('登录失败！' + res.errMsg)
      }
    },
    })
    }else{
      this.setData({
        long: options.long,
        lan: options.lan,
        redImg: wx.getStorageSync("parameter").zfFm,
        banrdId: options.banrdId ? options.banrdId : wx.getStorageSync("banrdId"),
        userId: wx.getStorageSync("userInfo").uid
      })
      var $this = this;
      var pamars = { banrdId: this.data.banrdId }
      ux.request(this.data.action, pamars, function (protocol) {
        console.log(JSON.stringify(protocol.data))
        $this.setData({
          lists: JSON.parse(protocol.data.card.tbpcProducts),
          card: protocol.data.card
        });
        $this.getAddressList(0);
        $this.getShar();
        WxParse.wxParse('articleDetail', 'html', protocol.data.card.tbpcXy, $this);
      }, true);
    }
  },
  getShar:function(){
    var self=this;
    var banrdid=wx.getStorageSync('banrdId');
    ux.request("/api/Merchant/getShars.do", {banrd:parseInt(banrdid),type:3},function(data){
      if(data.data.obj){
        self.setData({
          fenxiang:data.data.obj
        })
      }
    });
  },
  onForm: function (event) {
    if (this.data.submit) {
      var $this = this;
      var dataset = event.currentTarget.dataset;
      ux.request(this.data.submit, detail.value, function (protocol) {
        if (protocol.success) {
          if (dataset.url) {
            wx.redirectTo(dataset.url);
          }
        }
      }, true);
    }
  },
  preventTouchMoveTy: function () {
    return false;
  },
  jlzcOpen: function () {
    this.setData({
      jlzc: true
    })
  },
  dlxyOpen: function () {
    this.setData({
      dlxy: true
    })
  },
  jlzcX: function () {
    this.setData({
      jlzc: false
    })
  },
  dlxyX: function () {
    this.setData({
      dlxy: false
    })
  },
  onTap: function (event) {
    var dataset = event.currentTarget.dataset;
    var data = this.data;
    if (dataset.key && dataset.val) {
      data[dataset.key] = dataset.val;
    }
    this.setData(data);
  },
  tongyis: function () {
    if (this.data.tongyi == 2) {
      this.setData({
        tongyi: 1
      })
    } else {
      this.setData({
        tongyi: 2
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  liji: function () {
    this.setData({
      focus: true
    })
  },
  mobiles: function (e) {
    this.setData({
      mobile: e.detail.value
    })
  }, profiles: function (e) {
    this.setData({
      profile: e.detail.value
    })
  },
  names: function (e) {
    this.setData({
      name: e.detail.value
    })
  },
  youshis: function (e) {
    this.setData({
      youshi: e.detail.value
    })
  },
  /**城市 开始*/

  getAddressList: function (pid) {
    var self = this;
    var params = { pid: pid, banrdId: this.data.banrdId};
    wx.showLoading({
      mask: true,
      title: '正在加载...'
    })
    ux.request('/api/address/getAddressListByPidSub.do', params, function (data) {
      wx.hideLoading();
      var adressList = self.data.adressList;
      adressList[self.data.citytab] = data.data.list
      self.setData({
        adressList: adressList
      })
    }, true);
  },
  showCityPicker: function () {
    this.setData({
      showCityPicker: true,
      hosList: []
    })
  },
  tabClick: function (event) {
    var dataset = event.currentTarget.dataset;
    var index = dataset.index;
    this.setData({
      citytab: index
    })
    if (index == 0) {
      this.setData({
        selectsIndex: this.data.proviceIndex,
      })
    } else if (index == 1) {
      this.setData({
        selectsIndex: this.data.cityIndex,
      })
    } else if (index == 2) {
      this.setData({
        selectsIndex: this.data.countyIndex,
      })
    } else if (index == 3) {
      this.setData({
        selectsIndex: this.data.countryIndex,
      })
    }
  },
  selectThis: function (event) {
    var dataset = event.currentTarget.dataset;
    var idx = dataset.idx;
    var index = dataset.index;
    console.log(idx);
    var adressList = this.data.adressList;
    var tabs = this.data.citytabs;
    var id = adressList[idx][index].id;
    var tabName = adressList[idx][index].name;
    var newTabs = []
    var newList = []
    var idxtab = 0;

    if (idx == 0) {
      this.setData({
        provice: id,
        proviceIndex: index,
        city: null,
        county: null,
        country: null,
        cityIndex: -1,
        countyIndex: -1,
        countryIndex: -1,
      })
    } else if (idx == 1) {
      this.setData({
        city: id,
        county: null,
        country: null,
        cityIndex: index,
        countyIndex: -1,
        countryIndex: -1,
      })
    } else if (idx == 2) {
      this.setData({
        county: id,
        country: null,
        countyIndex: index,
        countryIndex: -1,
      })
    } else if (idx == 3) {
      this.setData({
        country: id,
        countryIndex: index,
      })
    }
    if (idx < 4) {
      for (var i = 0; i < tabs.length; i++) {
        newList[i] = adressList[i]
        if (i == idx) {
          newTabs[i] = tabName
          if (idx == 3) {
            idxtab = idx
            break;
          } else {
            newTabs.push("请选择");
            idxtab = idx + 1
            break;
          }
        } else {
          idxtab = idx;
          newTabs[i] = tabs[i]
        }
      }
      this.setData({
        adressList: newList,
        citytabs: newTabs,
        citytab: idxtab
      })
      if (idx != 3) {
        this.getAddressList(adressList[idx][index].id);
      } else {
        this.setData({
          selectsIndex: this.data.countryIndex,
        })
        this.okCityClick();
      }
    }
  },
  okCityClick: function () {
    var ps = '';
    var lists = this.data.adressList;

    if (this.data.proviceIndex >= 0) {
      ps = ps + lists[0][this.data.proviceIndex].name + ">";
    }
    if (this.data.cityIndex >= 0) {
      ps = ps + lists[1][this.data.cityIndex].name + ">";
    }
    if (this.data.countyIndex >= 0) {
      ps = ps + lists[2][this.data.countyIndex].name + ">";
    }
    if (this.data.countryIndex >= 0) {
      ps = ps + lists[3][this.data.countryIndex].name + ">";
    }
    this.setData({
      addressName: ps.substring(0, ps.length - 1),
      showCityPicker: false
    })
  },
  /**城市 结束*/
  toPay: function (e) {
    
    var self = this;
    if (!this.data.name) {
      this.toast("请输入联系人");
      this.setData({
        focus:true
      })
      return false;
    }
    if (!this.data.mobile) {
      this.toast("请输入联系电话");
      return false;
    }
    var regMobile = /^1\d{10}$/;
    if (!regMobile.test(this.data.mobile)) {
      this.toast("手机格式有误");
      return false;
    }
    if (!this.data.country) {
      this.toast("请选择所在城市");
      return false;
    }
    if (!this.data.sex) {
      this.toast("请选性别");
      return false;
    }
    if (!this.data.age) {
      this.toast("请选性别");
      return false;
    }
    if (!this.data.sr) {
      this.toast("请选收入");
      return false;
    }
    if (!this.data.zy) {
      this.toast("请选职业");
      return false;
    }
    if (this.data.tongyi == 2) {
      this.toast("请仔细阅读协议并同意");
      return false;
    }
    var pamars = {
      formId: e.detail.formId,
      longitude: this.data.long,
      latitude: this.data.lan,
      cardId: Number(this.data.card.id),
      name: this.data.name,
      mobile: this.data.mobile,
      profile: this.data.profile,
      sex:this.data.sex,
      age: this.data.age,
      sr: this.data.sr,
      zy: this.data.zy,
      youshi: this.data.youshi,
      banrdId: Number(this.data.banrdId),
      adressId: Number(this.data.country)
    }
    wx.showLoading({
      mask: true,
      title: '处理中....'
    })
    console.log(JSON.stringify(pamars))
    ux.request(this.data.torderUrl, pamars, function (data) {
      if (data.data.type) {
        var order = data.data;
        wx.requestPayment({
          timeStamp: order.timeStamp,
          nonceStr: order.nonceStr,
          package: order.package,
          signType: 'MD5',
          paySign: order.paySign,
          success: function (res) {
            pamars.orderNo=order.orderNo;
            ux.request("/api/memberAgent/HHRSave.do",pamars,function(e){
              wx.reLaunch({
                url: '/pages/member/tab1/sugarSpice?id=' + self.data.banrdId,
              })
            },true);
          },
          fail: function (res) {
            wx.showToast({
              title: "支付失败",
              duration: 3000
            })
            wx.hideLoading();
          }
        })
      } else if (!data.data.type) {
        wx.hideLoading()
        self.toast(data.data.msg);
      } else {
        wx.hideLoading()
        self.toast("支付失败");
      }
    }, true);
  },
  toast: function (params) {
    if (typeof (params) == "string") {
      params = { content: params };
    }
    this.setData({
      toast: params.content
    });
    var THIS = this;
    setTimeout(function () {
      THIS.setData({
        toast: false
      });
      if (params.complete) {
        params.complete();
      }
    }, params.time || 3000);
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      var self = this;
      self.setData({
        authModle: false
      })
      wx.showShareMenu({
        withShareTicket: true
      })
      var shareObj = {
        title: this.data.fenxiang.shareTitle,
        path: '/pages/member/tab1/agent/applyAgent?tab=1&userId=' + self.data.userId + "&banrdId=" + self.data.banrdId,
        imageUrl: this.data.fenxiang.url,
        success: function (res) {
          console.log(JSON.stringify(res));
        },
        fail: function () {
          wx.showToast({
            title: '转发失败',
          })
        }
      }
      return shareObj;
    } else {

    }
  },
})
